/*
 * Provide the style user experience after the window
 * load the code.
 *
 * More.
 */
window.onload = function()
{
    /**
     * Function to manipulate the effects by the search bar
     *
     */
    $(function() 
    {
        $(document).ready(function() 
        {
            var _input = document.getElementById("search_input");

            $("#search_input").click(function() {

                if (_input == "" || _input.value == 'search for products')
                    _input.value = "";

                $("#search_input").keypress(function(event) {

                    search_products($("#search_input").val());

                    document.getElementById("auto_complete").style.display = "block";

                });

                $("#search_input").animate({
                    color: "#020202",
                    width: 400
                }, 1000);

            });

            $("#search_input").focusout(function() {

                // Implement box resize 
                $("#search_input").animate({
                    color: "#666666",
                    width: 330
                }, 1000);

                // Change the input value if is empty to default.
                if (_input.value == "" || _input.value == undefined || _input.value == null)
                {
                    document.getElementById("search_input").value = "search for products";
                }

                // Hidden the auto complete bar.
                document.getElementById("auto_complete").style.display = "none";
            });
        });
    });

    /**
     * Function with ajax tecnique to query the products when
     * users start to type on search
     *
     */
    function search_products(key)
    {
        // Get the HTML request
        if (window.XMLHttpRequest)
        {
            request = new XMLHttpRequest();
        }
        else
        {
            request = new ActiveXObject("Microsoft.XMLHTTP");
        }

        // Function to listen state
        request.onreadystatechange = function()
        {
            if (request.readyState == 4 && request.status == 200)
            {
                document.getElementById("auto_complete").innerHTML = request.responseText;
            }
        }

        // Send the request
        request.open("GET", "images/ajax/search.php?valid=1&key=" + key);
        request.send();
    }
}
